<template>
  <div>
    <van-form @submit="userLogin">
      <van-cell-group inset>
        <van-field
          v-model="user.username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="user.pwd"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
        <van-button round block type="danger" native-type="reset"> 重置 </van-button>
        <van-button round block type="success" @click="router.push('/reg')">
          去注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts" name="LoginPage">
import { reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { userLog } from "@/api";
import { showSuccessToast, showFailToast } from "vant";
const router = useRouter();
const route = useRoute();
const user = reactive({
  username: "",
  pwd: "",
});
// 用户登录
const userLogin = () => {
  userLog({
    ...user,
    deviceId: "wert",
    deviceName: "dwferg",
  }).then((res) => {
    if (res.data.code === 0) {
      localStorage.setItem("token", res.data.data.token);
      localStorage.setItem("uid", res.data.data.uid);
      showSuccessToast({
        message: "登录成功",
        duration: 2000,
        onClose: () => {
          if (route.query.from) {
            router.replace(route.query.from);
          } else {
            router.replace("/home");
          }
        },
      });
    }
    if (res.data.code === 500) {
      showFailToast({
        message: res.data.msg,
      });
    }
  });
};
</script>

<style scoped></style>
